// 网关配置的前缀
var companyServer = "/companySer"
var jobsServer = "/jobsSer"

let companyId = $("#companyId").val();
let userId = ""
// let companyId = "1354255569179971586";
// let userId = "1354255569179971599"
let followedList = [];
let isFollowed = false;


var currentPage = 1;    // 当前页
var pageSize = 5;      // 页大小
var total = 0;          // 数据总量
var pages = 1;          // 页数总量

let bookmarkList = [];

let Authorization = "";
let refreshToken = "";

// 加载页面时读取后台的 ip
window.onload = function () {
    $.ajaxSettings.async = false;
    $.getJSON("/js/properties.json", function (data) {
        companyServer = data.companyServer;
        jobsServer = data.jobsServer;
    });
    // 获取令牌
    Authorization = getCookie("Authorization")
    refreshToken = getCookie("refreshToken")

    userId = $("#userId").html();
    // console.log(userId)
    getBookmarkList();
    getFollowedList()
    getCompanyInfo();
    getJobList(currentPage, pageSize, companyId)


    // 获取锚点, 并跳转
    let url = window.location.toString();
    let maoDian = "";
    if ($.inArray("#", url) >= 0){
        maoDian = url.split("#")[1];
        $('body,html').animate({
            scrollTop: ($("#"+maoDian).offset().top - 120) + "px"

        }, 200);
    }

}

function getFollowedList(){
    $.ajax({
        type: "POST",
        async: false,
        url: companyServer + "/company/getFollowedList",
        headers: {
            "Authorization": Authorization,
            "refreshToken": refreshToken,
        },
        data: {
            userId: userId,
        },
        success: function (data) {
            followedList = data.datas;
            if ($.inArray(companyId, followedList) >= 0){
                $("#followBut i").attr("hidden","hidden");
                $("#followBut img").removeAttr("hidden");
                isFollowed = true;
            }
        },
        error: function (err) {
            // 异常
            cocoMessage.error(2000, err.statusText, function () {
            });
        }
    })
}

function getCompanyInfo() {
    $.ajax({
        type: "GET",
        async: false,
        url: companyServer + "/company/selectOneCompany?companyId="+companyId,
        headers: {
            "Content-Type": "application/json",
            "Authorization": Authorization,
            "refreshToken": refreshToken,
        },
        success: function (data) {
            // 成功
            let company = data.datas;
            let pathLogo = company.logo;
            let pathPhoto = company.companyPhoto;

            if (pathLogo === "" || pathLogo === null) {

            } else {
                $("#companyLogo").attr("src",pathLogo);
            }

            if (pathPhoto === "" || pathPhoto === null) {

            } else {
                $("#companyPhoto").attr("src",pathPhoto);
            }


            $("#companyName").html(company.companyName);
            $(".companySize").html(company.companySize);
            $(".establishmentDate").html(company.establishmentDate);
            $(".enterprisesType").html(company.enterprisesType);
            $("#website").html(company.website);
            $("#companyAddress").html(company.companyAddress);
            $("#introduction").html(company.introduction);
            $("#legalRepresentative").html(company.legalRepresentative);
            $("#operationStatus").html(company.operationStatus);
            $("#registeredAddress").html(company.registeredAddress);
            $("#creditCode").html(company.creditCode);
            $("#businessNature").html(company.businessNature);

        },
        error: function (err) {
            // 异常
            cocoMessage.error(2000, err.statusText, function () {
            });
        }
    })
}

function followCompany(){
    let url = "";
    if (isFollowed){
        url = companyServer + "/company/cancelFollowCompany";
    }else {
        url = companyServer + "/company/followCompany";
    }
    $.ajax({
        type: "POST",
        async: false,
        url: url,
        headers: {
            "Authorization": Authorization,
            "refreshToken": refreshToken,
        },
        data: {
            userId: userId,
            companyId: companyId,
        },
        success: function (data) {
            if (data.resp_code === 0) {
                // 成功
                cocoMessage.info(2000, data.resp_msg, function () {
                });
                if (isFollowed){
                    console.log("取消收藏")
                    $("#followBut img").attr("hidden","hidden");
                    $("#followBut i").removeAttr("hidden");
                    isFollowed = false;
                }else {
                    console.log("收藏")
                    $("#followBut i").attr("hidden","hidden");
                    $("#followBut img").removeAttr("hidden");
                    isFollowed = true;
                }
            } else {
                // 失败
                cocoMessage.error(2000, data.resp_msg, function () {
                    console.log(data.resp_msg);
                });
            }
        },
        error: function (err) {
            // 异常
            cocoMessage.error(2000, err.statusText, function () {
                console.log(err);
            });
        }
    })
}

function getJobList(currentPage, pageSize,  companyId) {

    $.ajax({
        type: "get",
        async: false,
        url: jobsServer + "/jobs/jobInfo",
        headers: {
            "Authorization": Authorization,
            "refreshToken": refreshToken,
        },
        data: {
            currentPage: currentPage,
            pageSize: pageSize,
            deleted: 0,
            companyId: companyId,
            status: "正常"
        },
        success: function (data) {
            total = data.datas.total;
            pageSize = data.datas.size;
            pages = data.datas.pages;

            //清空数据
            $("#jobsList").empty();

            if (data.datas.records === null ||
                data.datas.records === "" ||
                data.datas.records.length <= 0){
                $("#jobsList").append(
                   " <div>暂无数据</div>"
                )
            }

            //返回的数据用data.rows获取内容
            $.each(data.datas.records, function (i, item) {
                let jobList = ["", "", "", ""];
                let temp = [];
                if (item.skills !== "" && item.skills !== null) {
                    temp = item.skills.split(",");
                    $.each(temp, function (i, skill) {
                        jobList[i] = skill;
                    })
                }

                let id = item.jobId;
                let aixin = "";
                if ($.inArray(id, bookmarkList) >= 0) {
                    aixin = "<img src='/images/aixin-2.png' style='width: 20px;height: 20px;' />";
                } else {
                    aixin = "<i class='far fa-heart'></i>";
                }

                $("#jobsList").append(
                    "<div class='col-lg-12 mb-20'>" +
                    "<div class='single-job style-two'>" +
                    "<div class='info-top'>" +
                    "<div class='job-info'>" +
                    "<div class='job-info-inner'>" +
                    "<div class='job-info-top'>" +
                    "<div class='saveJob for-listing'>" +
                    "<span class='featured-label'>精选</span>" +
                    "<a class='job-type-label ml-20 mr-20'>" + item.jobType + "</a>" +
                    "<a class='save-job' data-toggle='modal' disabled='disabled'>" +
                    aixin +
                    "</a>" +
                    "</div>" +
                    "<div class='title-name'>" +
                    "<h3 class='job-title'>" +
                    "<a onclick='jobDetail(\""+item.jobId+"\", \""+item.companyId+"\")'>" + item.jobName + "</a>" +
                    "</h3>" +
                    "<div class='employer-name'>" +
                    "<a onclick='companyDetail(\"" + item.companyId + "\")'>" + item.companyName + "</a>" +
                    "</div>" +
                    "</div>" +
                    "</div>" +
                    "<div class='job-meta-two'>" +
                    "<div class='field-salary_from'>" +
                    "￥&nbsp;" + item.salaryMin + "&nbsp;-&nbsp;" + item.salaryMax + "&nbsp;" + item.salaryUnit +
                    "</div>" +
                    "<div class='field-datetime'>" +
                    "<i class='lnr lnr-clock'></i>" + item.updateDate + "" +
                    "</div>" +
                    "</div>" +
                    "<div class=job-skill-tag>" +
                    "<a>" + jobList[0] + "</a>" +
                    "<a>" + jobList[1] + "</a>" +
                    "<a>" + jobList[2] + "</a>" +
                    "<a>" + jobList[3] + "</a>" +
                    "</div>" +
                    "</div>" +
                    "</div>" +
                    "</div>" +
                    "</div>" +
                    "</div>"
                );

            });

            // pageMe.js 使用方法
            $("#page").paging({
                pageNum: currentPage, // 当前页面
                totalNum: pages, // 总页码
                totalList: total, // 记录总数量
                pageSize: pageSize,
                callback: function (num, size) { //回调函数
                    pageSize = size;
                    currentPage = num;
                    getJobList(num, size, companyId)
                    // 返回顶部
                    if ($(window).scrollTop() > 200) {
                        $('body,html').animate({
                            scrollTop: ($("#jobsList").offset().top - 200) + "px"

                        }, 200);
                    }

                }
            });
        },
        error: function (err) {
            cocoMessage.error(2000, err.statusText, function () {
                console.log(err);
            });
        }

    });

}
function getBookmarkList() {
    $.ajax({
        type: "GET",
        async: false,
        url: jobsServer + "/jobs/getBookmarks?userId=" + userId,
        headers: {
            "Authorization": Authorization,
            "refreshToken": refreshToken,
        },
        success: function (data) {
            bookmarkList = data.datas;
        },
        error: function (err) {
            cocoMessage.error(2000, err.statusText, function () {
                console.log(err);
            });
        }
    })
}
function jobDetail(jobId, companyId){
    location.href ="/oa/jobs/jobDetails/"+jobId+"/"+companyId;
}
